// src/features/channels/api/use-update-channel.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {v4 as uuidv4} from 'uuid';

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    id: string
} | null

type ResponseType = {
    id: string
} | null

// client
export const useRemoveChannel = () => {
    // create db workspace

    const [data, setData] = useState<RequestType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        try {
            setData(null)
            setError(null)
            setStatus('pending')

            const cid = uuidv4()
            // 创建workspace的默认频道channel
            // const response = await fetch(`${MARK_DATA_URL}/channels/${values?.id}`, {
            const response = await fetch(`/api/channels/${values?.id}`, {
                method: 'DELETE',
            })

            if (response.ok) options?.onSuccess?.(cid)
            setStatus('success')
            return cid
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, isError, data
    }
}